import type {
  LoginState,
  LoginSuccessVo,
  OauthLoginState,
} from '#/auth/Login'
import type { SysUserUpdateLoginQo } from '#/system/user'
import type { UserState } from './types/user'
import { loginApi } from '@/api/auth'
import {
  getByLoginUserInfoApi,
  updateSysUserByLoginApi,
} from '@/api/system/user'
import router from '@/router'
import { initRouter } from '@/router/utils'
import { store } from '@/stores'

let isLogoutConfirm = false
export const useUserStore = defineStore(`${import.meta.env.VITE_NAMESPACE}-user`, {
  state: (): UserState => ({
    accessToken: '',
    refreshToken: '',
    user: {},
  }),
  actions: {
    /**
     * 获取token
     */
    getAccessToken() {
      return `Bearer ${this.accessToken}`
    },
    /**
     * 获取刷新token
     */
    getRefreshToken() {
      return this.refreshToken
    },
    /**
     * 获取租户id
     */
    getTenantId() {
      return this.user?.tenantId ?? null
    },
    /**
     * 设置登录成功
     * @param data
     */
    async setLoginSuccess(data: LoginSuccessVo) {
      this.accessToken = data.accessToken
      this.refreshToken = data.refreshToken
      this.setLoginUserInfo()
      initRouter()
    },

    /**
     * 更新登录用户信息
     */
    async updateLoginUserInfo(data: SysUserUpdateLoginQo) {
      await updateSysUserByLoginApi(data)
      await this.setLoginUserInfo()
    },
    /**
     * 获取登录用户信息
     */
    async setLoginUserInfo() {
      const res = await getByLoginUserInfoApi()
      this.user = res.data
    },
    async login(form: LoginState | OauthLoginState) {
      return new Promise<LoginSuccessVo>((resolve, reject) => {
        loginApi(form).then((res) => {
          this.setLoginSuccess(res.data)
          resolve(res.data)
        }).catch((err) => {
          reject(err)
        })
      })
    },
    async logout(confirm: boolean = false) {
      if (confirm && !isLogoutConfirm) {
        isLogoutConfirm = true
        ElMessageBox.confirm(
          '当前登录会话已失效，请重新登录',
          '提示',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          },
        )
          .then(() => {
            router.push('/login')
          })
          .catch(() => {
          })
          .finally(() => {
            isLogoutConfirm = false
          })
      }
      else {
        router.push('/login')
      }
      this.accessToken = ''
      this.refreshToken = ''
      this.user = {}
    },
  },
  persist: true,
})

export function useUserStoreHook() {
  return useUserStore(store)
}
